package com.didi.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.didi.gulimall.api.CouponApiService;
import com.didi.gulimall.api.SearchApiService;
import com.didi.gulimall.api.WareApiService;
import com.didi.gulimall.common.constant.ProductConstant;
import com.didi.gulimall.common.to.SkuHasStockVo;
import com.didi.gulimall.common.to.SkuReductionTo;
import com.didi.gulimall.common.to.SpuBoundTo;
import com.didi.gulimall.common.to.es.SkuEsModel;
import com.didi.gulimall.common.utils.R;
import com.didi.gulimall.product.dao.SpuInfoDao;
import com.didi.gulimall.product.entity.*;
import com.didi.gulimall.product.service.*;
import com.didi.gulimall.product.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.didi.gulimall.common.utils.PageUtils;
import com.didi.gulimall.common.utils.Query;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponApiService couponApiService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private WareApiService wareApiService;
    @Autowired
    private SearchApiService searchApiService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );
        return new PageUtils(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSpuInfo(SpuSaveVo spuVo) {
        //1、保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuVo, spuInfoEntity);
        spuInfoEntity.setUpdateTime(new Date());
        spuInfoEntity.setCreateTime(new Date());
        this.save(spuInfoEntity);
        Long spuId = spuInfoEntity.getId();
        //2、保存Spu的描述图片 pms_spu_info_desc
        List<String> decript = spuVo.getDecript();
        SpuInfoDescEntity decriptEntity = new SpuInfoDescEntity();
        decriptEntity.setSpuId(spuId);
        decriptEntity.setDecript(String.join(",", decript));
        spuInfoDescService.save(decriptEntity);

        //3、保存spu的图片集 pms_spu_images
        List<String> images = spuVo.getImages();
        spuImagesService.saveImages(spuId, images);
        //4、保存spu的规格参数;pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuVo.getBaseAttrs();
        AtomicReference<Integer> attrSort = new AtomicReference<>(0);
        List<ProductAttrValueEntity> attrValueEntities = baseAttrs.stream().map(base -> {
            ProductAttrValueEntity attrValueEntity = new ProductAttrValueEntity();
            BeanUtils.copyProperties(base, attrValueEntity);
            attrValueEntity.setAttrValue(base.getAttrValues());
            attrValueEntity.setQuickShow(base.getShowDesc());
            attrValueEntity.setSpuId(spuId);
            attrValueEntity.setAttrSort(attrSort.get());
            AttrEntity attr = attrService.getById(base.getAttrId());
            attrValueEntity.setAttrName(attr.getAttrName());
            attrSort.updateAndGet(v -> v + 1);
            return attrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(attrValueEntities);
        //5、保存spu的积分信息；gulimall_sms->sms_spu_bounds
        Bounds bounds = spuVo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuId);
        R r = couponApiService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }
        //5、-------------保存当前spu对应的所有sku信息； -------------

        List<Skus> skus = spuVo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(skuVo -> {
                String defaultImg = "";
                for (Images image : skuVo.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }
                //5.1）、sku的基本信息；pms_sku_info
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(skuVo, skuInfoEntity);
                skuInfoEntity.setCatalogId(spuVo.getCatalogId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuId);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoService.save(skuInfoEntity);
                Long skuId = skuInfoEntity.getSkuId();
                //5.2）、sku的图片信息；pms_sku_image
                List<SkuImagesEntity> collect = skuVo.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    return skuImagesEntity;
                }).filter(entity -> {
                    //返回true就是需要，false就是剔除
                    return StringUtils.isNotBlank(entity.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(collect);
                //5.3）、sku的销售属性信息：pms_sku_sale_attr_value
                List<Attr> attr = skuVo.getAttr();
                List<SkuSaleAttrValueEntity> attrValues = attr.stream().map(item -> {
                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(item, attrValueEntity);
                    attrValueEntity.setSkuId(skuId);
                    return attrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(attrValues);
                // //5.4）、sku的优惠、满减等信息；gulimall_sms->sms_sku_ladder\sms_sku_full_reduction\sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                skuReductionTo.setOriginalPrice(skuInfoEntity.getPrice());
                BeanUtils.copyProperties(skuVo, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(BigDecimal.ZERO) > 0) {
                    R result = couponApiService.saveSkuReduction(skuReductionTo);
                    if (result.getCode() != 0) {
                        log.error("远程保存sku优惠信息失败");
                    }
                }
            });
        }


    }

    @Override
    public void updateSpuUp(Long spuId) {
        //1、查出当前spuid对应的所有sku信息，品牌的名字。
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);
        if (skus==null || skus.size()==0){
            throw new RuntimeException("该"+spuId+"号spu底下没有任何商品");
        }
        List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.listforspu(spuId);
        List<Long> attrIds = baseAttrs.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);

        Set<Long> idSet = new HashSet<>(searchAttrIds);
        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs);
            return attrs;
        }).collect(Collectors.toList());

        Map<Long, Boolean> stockMap = null;
        try {
            R r = wareApiService.getSkusHasStock(skuIds);
            if (r.getCode()==0){
                TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {};
                stockMap = r.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
            }
        } catch (Exception e) {
            log.error("库存服务查询异常:原因{}", e);
        }
        //2、封装每个sku的信息
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> esModels = skus.stream().map(skuInfo -> {
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(skuInfo, esModel);
            esModel.setSkuImg(skuInfo.getSkuDefaultImg());
            esModel.setSkuPrice(skuInfo.getPrice());
            BrandEntity brand = brandService.getById(skuInfo.getBrandId());
            esModel.setBrandImg(brand.getLogo());
            esModel.setBrandName(brand.getName());
            CategoryEntity category = categoryService.getById(skuInfo.getCatalogId());
            esModel.setCatalogName(category.getName());
            esModel.setAttrs(attrsList);
            // TODO 评分系统
            esModel.setHotScore(0L);
            if (finalStockMap!=null){
                esModel.setHasStock(finalStockMap.get(skuInfo.getSkuId()));
            }else {
                esModel.setHasStock(true);
            }
            return esModel;
        }).collect(Collectors.toList());
        R r = searchApiService.productStatusUp(esModels);
        if (r.getCode()==0){
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }
    }

}